import React, { Component} from 'react'
import { Card, Breadcrumb, Form, Button, Input, Radio, Space, Upload, Modal, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

import { ArticlePublishWrapper } from './style'

import Channel from '@/components/Channel'
import { addArticle, getArticleById, editArticleById } from '@/api/article.js'

export default class ArticlePublish extends Component {
  state = {
    // 存放上传的文件列表
    fileList: [
      //   {
      //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      //   },
    ],
    type: 0, // 控制图片上传的数量
    previewVisible: false,
    previewImage: '',
    isEdit: !!this.props.match.params.id,
    id: this.props.match.params.id
  }

formRef = React.createRef()
//2. 发布 
onFinish = async (values) => {
    this.save(values, false)
}
//   加入草稿
addDraft = async() => {
    let values = await this.formRef.current.getFieldsValue()

    this.save(values, true)
}


//   抽取公共部分
save = async (values, draft) => {
    let { isEdit } = this.state
// 图片校验
if (this.state.type !== this.state.fileList.length) {
    return message.warn('上传的图片数量不对')
  }

  //  收集值1：3个参数已经集齐 values {...value}
  // 收集参数2：一个参数cover 需要我们手动配置
  // cover : {type, images}
  const data = {
    ...values,
    cover: {
      type: values.type,
      images: this.state.fileList.map(v => v.url || v.response.data.url),
    },
  }

  // 发布文章
  try {
    if(isEdit) {
        let res = await editArticleById(this.props.match.params.id, data, draft)
        console.log(res.data)
        message.success('修改文章成功')
    } else {
        await addArticle(data, draft)
        message.success('添加文章成功')
    }
   
    // 跳转
    this.props.history.push('/home/articlelist')
  } catch (error) {
    message.error('发布失败')
  }
}
  beforeUpload = file => {
    if (file.size / 1024 > 100) {
      message.error('上传的图片过大, 超过了500KB!!')
      return Upload.LIST_IGNORE
    }
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.error('图片类型, 仅支持jpeg, png')
      return Upload.LIST_IGNORE
    }

    return true
  }
  //   处理图片上传的数量
  changeImageType = e => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  // 上传图片
  uploadImages = ({ file, fileList }) => {
    this.setState({
      fileList,
    })
  }

  //   图片预览
  handlePreview = file => {
    this.setState({
      previewVisible: true,
      previewImage: file.url || file.response.data.url,
    })
  }
  //   预览取消
  handleCancel = () => {
    this.setState({
      previewVisible: false,
      previewImage: '',
    })
  }
  render() {
    return (
      <ArticlePublishWrapper>
        <div className="ArticlePublish">
          <Card
            title={
              <Breadcrumb separator=">">
                <Breadcrumb.Item href="/home">首页</Breadcrumb.Item>
                <Breadcrumb.Item>{this.state.isEdit ? '修改文章' : '发布文章'}</Breadcrumb.Item>
              </Breadcrumb>
            }
          >
            <Form
              ref={this.formRef}
              labelCol={{ span: 4 }}
              initialValues={{ type: 0, content: '' }}
              onFinish={this.onFinish}
            >
              <Form.Item
                label="标题"
                name="title"
                rules={[{ required: true, message: '请输入文章标题' }]}
              >
                <Input placeholder="请输入文章标题" style={{ width: 400 }} />
              </Form.Item>
              <Form.Item
                label="频道"
                name="channel_id"
                rules={[{ required: true, message: '请选择文章频道' }]}
              >
                <Channel />
              </Form.Item>
              <Form.Item label="封面">
                <Form.Item name="type">
                  <Radio.Group onChange={this.changeImageType}>
                    <Radio value={0}>无图</Radio>
                    <Radio value={1}>单图</Radio>
                    <Radio value={3}>三图</Radio>
                  </Radio.Group>
                </Form.Item>
                {this.state.type !== 0 && (
                  <Upload
                    listType="picture-card"
                    name="image"
                    action={`http://geek.itheima.net/v1_0/upload`}
                    onChange={this.uploadImages}
                    fileList={this.state.fileList}
                    onPreview={this.handlePreview}
                    beforeUpload={this.beforeUpload}
                  >
                    {this.state.fileList.length < this.state.type && <PlusOutlined></PlusOutlined>}
                  </Upload>
                )}
              </Form.Item>
              <Form.Item
                label="内容"
                name="content"
                rules={[{ required: true, message: '请输入文章内容' }]}
              >
                {/* 富文本 */}
                <ReactQuill theme="snow" placeholder="请输入文章内容..."></ReactQuill>
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Space>
                  <Button size="large" type="primary" htmlType="submit">
                  {this.state.isEdit ? '修改文章' : '发布文章'}
                  </Button>
                  <Button size="large" onClick={this.addDraft}>存入草稿</Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
          <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
            <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
          </Modal>
        </div>
      </ArticlePublishWrapper>
    )
  }

  
 async componentDidMount() {
    let { isEdit } = this.state
 //    判断根基id发送请求
 if (isEdit) {
     // 根据 id 发送请求
     const res = await getArticleById(this.state.id)
     let { title, channel_id, content, cover } = res.data.data
 
     // 1. state中 type 和 fileList 需要更新
     this.setState({
       type: cover.type,
       fileList: cover.images.map(url => ({url})),
     })
     // 2. 表单中的数据也需要更新
     this.formRef.current.setFieldsValue({
       title,
       channel_id,
       content,
       type: cover.type,
     })
   }
  }
}
